﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using GameFramework.common;
using NettyDeomo.entity;
using NettyDeomo.msg;
using UnityEngine;

namespace NettyDeomo.handler
{
    public class MsgHandler : MonoSingleton<MsgHandler>
    {
        ConcurrentQueue<object> msgQue = new ConcurrentQueue<object>();


        public Player player;

        private void Update()
        {
            object msg;
            if (msgQue.Count > 0)
            {
                //TODO 过场景的时候暂停处理
                
                while (msgQue.TryDequeue(out msg))
                {
                    //TOD 检测是否在过场景中，是的话先暂停解析消息
                    handleMsg(msg);
                }
            }
        }

        public void handle(object msg)
        {
            msgQue.Enqueue(msg);
            // if (!)
            // {
            //     Debug.LogError("消息如队列失败：" + msg.GetType().Name);
            // }
        }



        private void handleMsg(object msg)
        {
            #region S2C
            if (msg is S2C_SyncId)
            {
                handle_S2C_SyncId(msg as S2C_SyncId);
                return;
            }

            if (msg is S2C_EnterMap)
            {
                handle_S2C_EnterMap(msg as S2C_EnterMap);
                return;
            }

            if (msg is S2C_SynAroundObjs)
            {
                handle_S2C_SynAroundMonster(msg as S2C_SynAroundObjs);
                return;
            }

            if (msg is S2C_MonsterMoveTo)
            {
                handle_S2C_MonsterMoveTo(msg as S2C_MonsterMoveTo);
                return;
            }
            if (msg is S2C_PlayerMove)
            {
                handle_S2C_PlayerMove(msg as S2C_PlayerMove);
                return;
            }
            #endregion
            
        }

        private void handle_S2C_PlayerMove(S2C_PlayerMove msg)
        {
            Player find = GameMap.Instance.players.Find(p=>p.Id==msg.id);
            if (find == null)
            {
                Debug.Log("未找到移动玩家数据！");
                return;
            }

            find.moveDir.x = msg.x;
            find.moveDir.z = msg.y;
            find.speed = msg.speed;
            find.isMoving = true;

            // Debug.Log("[" + DateTime.Now.ToString("hh:mm:ss t z") + "] 跟新玩家移动数据！");
        }


        private void handle_S2C_MonsterMoveTo(S2C_MonsterMoveTo msg)
        {
            List<Monster> monsters = GameMap.Instance.monsters;
            Monster monster = monsters.Find(m => m.id == msg.id);
            if (monster != null)
            {
                Debug.LogWarning("怪物当前坐标：" + monster.gameObject.transform.position + "  旧目标：" +
                                 monster.moveTarget.ToString() + "  新目标：" + msg.x.ToString() + "  " + msg.y.ToString());
                monster.moveTarget.x = (float)msg.x;
                monster.moveTarget.z = (float)msg.y;
                monster.isMoving = true;
                // Debug.Log("同步怪物移动目标点！");
            }
        }

        private void handle_S2C_SynAroundMonster(S2C_SynAroundObjs msg)
        {
            //
            Debug.Log("同步周围对象！");
            List<MonsterData> msgMonsterList = msg.monsterList;
            foreach (var monster in msgMonsterList)
            {
                Monster find = GameMap.Instance.monsters.Find(m => m.id == monster.id);
                if (find != null)
                {
                    // find.pos = monster.pos;
                    find.gameObject.transform.position = new Vector3(monster.posX, 0, monster.posY);
                    // find.moveTarget = monster.moveTarget;
                    find.moveTarget.x = monster.moveTargetX;
                    find.moveTarget.z = monster.moveTargetY;
                    find.speed = monster.speed;
                    find.isMoving = true;
                }
                else
                {
                    GameObject load = UnityEngine.Resources.Load<GameObject>("Prefabs/NettyDemo/Monster");
                    if (load != null)
                    {
                        Debug.Log("创建monster实例");
                        GameObject instantiate = GameObject.Instantiate(load);
                        Monster monsterObj = instantiate.GetComponent<Monster>();
                        Debug.Log("创建的monster：" + monsterObj);
                        monsterObj.Id = monster.id;

                        monsterObj.gameObject.transform.position = new Vector3(monster.posX, 0, monster.posY);
                        monsterObj.moveTarget.x = monster.moveTargetX;
                        monsterObj.moveTarget.z = monster.moveTargetY;
                        monsterObj.isMoving = true;
                        GameMap.Instance.monsters.Add(monsterObj);
                    }
                }
            }
            List<PlayerData> msgPlayerList = msg.playerList;
            foreach (PlayerData playerData in msgPlayerList)
            {
                Player find = GameMap.Instance.players.Find(p=>p.Id==playerData.id);
                if (find != null)//已存在，更新状态
                {
                    find.transform.position = new Vector3(playerData.posX, 0, playerData.posY);
                    find.speed = playerData.speed;
                    find.moveDir.x = playerData.moveDirX;
                    find.moveDir.y = playerData.moveDirY;
                    find.isMoving = true;
                }
                else
                {
                    GameObject load = UnityEngine.Resources.Load<GameObject>("Prefabs/NettyDemo/OtherPlayer");
                    if (load != null)
                    {
                        //创建新玩家
                        GameObject playerObj = GameObject.Instantiate(load);
                        Player p = playerObj.GetComponent<Player>();
                        if (p != null)
                        {
                            p.Id = playerData.id;
                            p.transform.position = new Vector3(playerData.posX, 0, playerData.posY);
                            p.speed = playerData.speed;
                            p.moveDir.x = playerData.moveDirX;
                            p.moveDir.y = playerData.moveDirY;
                            p.isMoving = true;
                            GameMap.Instance.players.Add(p);
                        }
                        else
                        {
                            Debug.Log("在创建的实例上未找到Player组件！");
                        }

                    }
                }
            }
        }

        private void handle_S2C_EnterMap(S2C_EnterMap msg)
        {
            //服务器主动通知进入地图
            //TODO 加载地图，显示过场景动画
            //地图加载完成后显示地图，将玩家放入地图中
            //向服务端发送进入成功的消息
            C2S_EnterMapSuccess resp = new C2S_EnterMapSuccess();
            resp.mapId = 1;
            NettyClient.Instance.sendMessage(resp);
        }

        private void handle_S2C_SyncId(S2C_SyncId msg)
        {
            int id = msg.playerId;
            Debug.Log("主玩家id：" + id);

            //发送进入地图的消息

            GameObject mainPlayer = GameObject.FindWithTag("Player");
            if (mainPlayer != null)
            {
                mainPlayer.GetComponent<Player>().isMainPlayer = true;
            }
            else
            {
                GameObject load = UnityEngine.Resources.Load<GameObject>("Prefabs/NettyDemo/OtherPlayer");
                mainPlayer = Instantiate(load);
                if (mainPlayer != null)
                {
                    Player player = mainPlayer.GetComponent<Player>();
                    player.isMainPlayer = true;
                }
            }
            GameMap.Instance.players.Add(mainPlayer.GetComponent<Player>());
        

            C2S_EnterMap enterMap = new C2S_EnterMap();
            enterMap.x = mainPlayer.transform.position.x;
            enterMap.y = mainPlayer.transform.position.y;
            NettyClient.Instance.sendMessage(enterMap);
            Debug.Log("发送C2S_EnterMap");
        }
        
    }
}